package user

import (
	"context"
	"fmt"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
)

// GetFundsDetailByUid 通过用户id获取用户资金信息
func (u *sUser) GetFundsDetailByUid(ctx context.Context, uid uint) (detail *entity.UserFunds, err error) {
	detail = &entity.UserFunds{}
	// 获取资金信息
	if err = u.FundsModel().DetailPri(ctx, uid, &detail); err != nil {
		return nil, exception.New(`用户资金信息数据异常`)
	}
	return
}

// UpdateFundsCoinByUid 通过用户ID更新用户盘古币
func (u *sUser) UpdateFundsCoinByUid(ctx context.Context, uid, coin uint, up bool) error {
	var (
		data    = g.Map{}
		columns = dao.UserFunds.Columns()
	)
	// 盘古币变更类型
	switch up {
	case true:
		// 增加盘古币
		data[columns.PanguCoinTotal] = gdb.Raw(fmt.Sprintf(`%s + %d`, columns.PanguCoinTotal, coin))
		data[columns.AvailablePanguCoin] = gdb.Raw(fmt.Sprintf(`%s + %d`, columns.AvailablePanguCoin, coin))
	default:
		// 消费盘古币
		data[columns.AvailablePanguCoin] = gdb.Raw(fmt.Sprintf(`%s - %d`, columns.AvailablePanguCoin, coin))
		data[columns.ConsumeTotalPanguCoin] = gdb.Raw(fmt.Sprintf(`%s + %d`, columns.ConsumeTotalPanguCoin, coin))
	}
	// 更新资金
	return u.UpdateFundsByUid(ctx, uid, data)
}

// UpdateFundsByUid 通过用户ID更新用户资金
func (u *sUser) UpdateFundsByUid(ctx context.Context, uid uint, data interface{}) error {
	if uid == 0 || data == nil {
		return exception.New(`更新用户资金缺少参数`)
	}
	err := u.FundsModel().Update(ctx, g.Map{
		dao.UserFunds.Columns().UserId: uid,
	}, data)
	if err != nil {
		return exception.New(`更新用户资金失败`)
	}
	return nil
}

// GetAndValidateFundsCoinsByUid 获取并验证用户资金盘古币可用金额
func (u *sUser) GetAndValidateFundsCoinsByUid(ctx context.Context, uid, coins uint) (detail *entity.UserFunds, err error) {
	// 获取账户资金
	if detail, err = u.GetFundsDetailByUid(ctx, uid); err != nil {
		return nil, err
	}
	// 验证可用盘古币
	if detail.AvailablePanguCoin < coins {
		return nil, exception.Newf(`余额不足，可用盘古币%d`, detail.AvailablePanguCoin)
	}
	return
}
